#!/usr/bin/env python
# vim: tabstop=4 : expandtab : shiftwidth=4

from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import yaml
import thing

possibleSlots = ['mainhand', 'offhand', 'head', 'face', 'ears', 'fingers', 'neck', 'torso', 'waist', 'legs', 'feet']
archtypes = ['edged', 'blunt', 'axe', 'ranged', 'piercing', 'throwing']

class ItemEditor(tkSimpleDialog.Dialog): # Inherit froma basic popup dialog
    def __init__(self, parent, item):
        "Store a reference to item in self, for later use."
        self.item = item
        tkSimpleDialog.Dialog.__init__(self, parent, "Item Editor")

    def body(self, root):
        "Create the form to be filled out."

        Label(root, text="Object status", font=("Helvetica", 14)).grid(row=0, column=0, columnspan=4, pady=5)
        # Name box
        Label(root, text="Name").grid(row=1, column=0)
        self.namebox = Entry(root)
        self.namebox.grid(row=1, column=1)
        self.namebox.insert(0, self.item.name) # Fill out the box with the value already in self.item
        # Description box
        Label(root, text="Description").grid(row=1, column=2)
        self.descbox = Entry(root)
        self.descbox.grid(row=1, column=3)
        self.descbox.insert(0, self.item.desc)
        # Slot box
        self.slotbox = StringVar(root)
        self.slotbox.set(self.item.slot)
        Label(root, text="Weapon slot").grid(row=2, column=0)
        OptionMenu(root, self.slotbox, *possibleSlots).grid(row=2, column=1)

        # Architecture box
        self.archbox = StringVar(root)
        self.archbox.set(self.item.arch)
        Label(root, text="Architecture").grid(row=2, column=0)
        OptionMenu(root, self.archbox, *archtypes).grid(row=2, column=3)

        Label(root, text="Attribute Bonuses", font=("Helvetica", 14)).grid(row=3, column=0, columnspan=4, pady=5)

        self.attrboxes = {}
        x=0
        y=0
        for idx,key in enumerate(self.item.bonus.keys()):
            if len(key) == 3:
                Label(root, text=key).grid(row=x + 4, column=0)
                self.attrboxes[key] = Entry(root)
                self.attrboxes[key].grid(row=x + 4, column=1)
                x+=1
            else:
                Label(root, text=key).grid(row=y + 4, column=2)
                self.attrboxes[key] = Entry(root)
                self.attrboxes[key].grid(row=y + 4, column=3)
                y+=1
            self.attrboxes[key].insert(0, self.item.bonus[key])


    def validate(self):
        "Check the form for valid input. Return True if all good, False (and show an error message) otherwise."
        if not self.namebox.get().strip():
            tkMessageBox.showerror("Error", "Invalid name.")
            return False
        if not self.descbox.get().strip():
            tkMessageBox.showerror("Error", "Invalid description.")
            return False
        if self.slotbox.get().strip() not in possibleSlots:
            tkMessageBox.showerror("Error", "You have entered a non existant item slot, or didn't enter anything at all.")
            return False
        """if self.slotbox.get().strip() != 'mainhand' or self.slotbox.get().strip() != 'offhand':
            if self.archbox.get().strip() != "":
                tkMessageBox.showerror("Pause, Dwag!", "Either your item is not slotted right, or you gave a non weapon a weapon property... go fix that!")
                return False"""

        for value in self.attrboxes.values():
            try:
                if int(value.get().strip()):
                    pass
            except ValueError:
                tkMessageBox.showerror("Error", value.get()+" is an invalid value.")
                return False

        return True

    def apply(self):
        "Fill in self.item.<stuff> when the OK button is clicked and the form has already been validate()'d."
        self.item.name = self.namebox.get().strip()
        self.item.desc = self.descbox.get().strip()
        for key,attrbox in self.attrboxes.items():
            self.item.bonus[key] = int(attrbox.get().strip())
        self.item.slot = self.slotbox.get().strip()
        self.item.arch = self.archbox.get().strip()

class ItemSelector:
    def __init__(self):
        self.root = Tk()
        self.root.title("Gilmud Equipable Item Editor")
        Label(self.root, text="Item List").grid(row=0, column=0, padx=10, pady=5, columnspan=2)
        self.lb = Listbox(self.root, height=25)
        self.lb.grid(row=1, column=0, padx=10, pady=10)

        buttonarea = Frame(self.root)
        buttonarea.grid(row=1, column=1, padx=10, pady=5)

        Button(buttonarea, text="New", command=self.createNewEquipable).pack()
        Button(buttonarea, text="Edit", command=self.editItem).pack()
        Button(buttonarea, text="Delete", command=self.deleteItem).pack()
        Button(buttonarea, text="Save", command=self.save).pack()
        Button(buttonarea, text="Save & Quit", command=self.end).pack()

        self.load()
        self.update()

        mainloop()
    def load(self):
        try:
            f = open("prefabs.yml")
        except IOError:
            self.items = {}
            return
        with f:
            self.items = yaml.load(f)

    def save(self):
        with open("prefabs.yml", "w") as f:
            yaml.dump(self.items, f)

    def update(self):
        for name,item in self.items.items():
            if item.name != name:
                self.items[item.name] = item
                del self.items[name]

        self.lb.delete(0, END)
        for item in self.items.keys():
            self.lb.insert(0, item)

    def editItem(self):
        currentSelection = self.lb.curselection()
        if len(currentSelection) != 1:
            tkMessageBox.showerror("Error", "There is no item selected.")
            return
        try:
            item = self.items[self.lb.get(currentSelection)]
        except KeyError:
            tkMessageBox.showerror("O_o", "No such name has been found in the database.")
            self.update()
            return
        ItemEditor(self.root, item)
        self.update()
        self.save()

    def deleteItem(self):
        selection = self.lb.curselection()
        if len(selection) != 1:
            tkMessageBox.showerror("Error", "There is no item selected.")
            return
        if not tkMessageBox.askyesno("Question", "Really permanantly delete the selected prefab?"):
            return
        try:
            del self.items[self.lb.get(selection)]
        except KeyError:
            tkMessageBox.showerror("Error", "Error deleting item, it was not found in the database (this should not be possible).")
            self.update()
            return
        self.update()
        self.save()
        return

    def createNewEquipable(self):
        name = tkSimpleDialog.askstring(" ", "    Name your new item.", initialvalue="", parent=self.root)
        if name == None: # User clicked cancel
            return
        name = name.strip()
        if name == "":
            tkMessageBox.showerror("Error", "That is not a valid name.")
            return
        newEquip = thing.Equipable()
        newEquip.name = name
        self.items[name] = newEquip
        itemlist = []
        for name,item in self.items.items():
            itemlist.append(item.uid)
        item.uid = max(itemlist)+1
        self.update()

    def end(self):
        self.save()
        self.root.destroy()

if __name__ == "__main__":
    ItemSelector()
